package name.vaccari.matteo.tai.chat.persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DatabaseExecutor {

	private DatabaseConnector connector;
	private Connection connection;
	
	public DatabaseExecutor(DatabaseConnector connector) {
		this.connector = connector;
	}

	public void execute(String sql, Object ... params) {
		Connection connection = getConnection();
		PreparedStatement statement = null;
		try {
			statement = connection.prepareStatement(sql);
			for (int i=0; i<params.length; i++) {
				statement.setObject(i+1, params[i]);
			}
			statement.executeUpdate();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			safelyClose(statement);
		}
	}

	public <T> List<T> select(String sql, Mapper<T> mapper, Object ... parameters) {
		Connection connection = getConnection();
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			statement = connection.prepareStatement(sql);
			addParameters(statement, parameters);
			resultSet = statement.executeQuery();
			return collectResults(mapper, resultSet);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			safelyClose(resultSet);
			safelyClose(statement);
		}
	}

	private void addParameters(PreparedStatement statement, Object[] parameters) throws SQLException {
		for (int i=0; i<parameters.length; i++) {
			statement.setObject(i+1, parameters[i]);
		}
	}

	private <T> List<T> collectResults(Mapper<T> mapper, ResultSet resultSet) throws SQLException {
		List<T> result = new ArrayList<T>();
		while (resultSet.next()) {
			T object = mapper.map(resultSet);
			result.add(object);
		}
		return result;
	}
	
	private Connection getConnection() {
		if (null == connection) {
			connection = connector.getConnection();
		}
		return connection;
	}

	private void safelyClose(ResultSet resultSet) {
		if (null != resultSet) {
			try {
				resultSet.close();
			} catch (SQLException ignored) {
			}
		}
	}

	private void safelyClose(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException ignored) {
			}
		}
	}

	private void safelyClose(Statement statement) {
		if (null != statement) {
			try {
				statement.close();
			} catch (SQLException ignored) {
			}
		}
	}

	public void closeConnection() {
		safelyClose(connection);
	}

}
